import React, { useState, useEffect } from 'react'
import Taro, { useLoad } from '@tarojs/taro'
import {
  View,
  Text,
  Button,
  ScrollView,
  RadioGroup,
  Radio,
  CheckboxGroup,
  Checkbox,
  Input
} from '@tarojs/components'
import './index.scss'

// type QuestionType = 'single' | 'multiple' | 'text'

interface Option {
  [key: string]: string; // 动态键，值为字符串，如 { "A": "TT" }
}

// 定义题目接口
interface Question {
  id: number
  type: string
  title: string
  options?: Option[]
  answer?: string | string[]
  correctAnswer: string | string[] // 正确答案
  analysis: string // 答案解析
}


// 定义问卷数据接口
interface Questionnaire {
  id: number
  title: string
  description: string
  questions: Question[]
}

// 接口响应类型
interface ApiResponse<T> {
  success: boolean
  data: T
}

// 定义答题状态接口
type AnswerStatus = Record<number, 'correct' | 'incorrect'>

const ret: ApiResponse<Questionnaire> = {
              
                success: false,
                "data": {
                  "id": 1,
                  "title": "NO1",
                  "description": "description1",
                  "questions": [{
                    "id": 1,
                    "type": "single",
                    "title": "name pls",
                    "options": [{"A": "TT"}, {"B": "JDG"}, {"C": "T1"}, {"D": "AG"}],
                    "answer": [],
                    "correctAnswer": "A",
                    "analysis": "AAAAA"
                  },
                  {
                    "id": 2,
                    "type": "single",
                    "title": "what you home",
                    // "options": [{"A": "111111T"}, {"B": "22222G"}, {"C": "33333"}, {"D": "4444"}],
                    "answer": [],
                    "correctAnswer": "C",
                    "analysis": "CCCCC"
                  },
                  {
                    "id": 3,
                    "type": "single",
                    "title": "OOXX is what",
                    // "options": [{"A": "fagf"}, {"B": "fgh"}, {"C": "67hg"}, {"D": "jkkl"}],
                    "answer": [],
                    "correctAnswer": "C",
                    "analysis": "CCCCC"
                  }
                ]}
              }
            

export default function Index () {
  useLoad(() => {
    console.log('question Page loaded.')
  })

  const [questionnaire, setQuestionnaire] = useState<Questionnaire | null>(null)
  const [loading, setLoading] = useState<boolean>(true)
  const [error, setError] = useState<string | null>(null)
  const [currentIndex, setCurrentIndex] = useState<number>(0)
  const [currentAnswerStatus, setCurrentAnswerStatus] = useState<boolean>()
  const [answerStatus, setAnswerStatus] = useState<Record<number, 'correct' | 'incorrect'>>({}) // 答题状态
  const [showAnalysis, setShowAnalysis] = useState<boolean>(false) // 是否显示解析
  

  // 获取问卷数据
  const fetchQuestionnaire = async (id: number) => {
    try {
      setLoading(true)
      // const res = await Taro.request<ApiResponse<Questionnaire>>({
      //   url: `https://api.example.com/questionnaires/ ${id}?withCorrectAnswers=true`,
      //   method: 'GET'
      // })
      const res = ret

      if (res.success) {
        setQuestionnaire(res.data)
      } else {
        setError('数据加载失败')
      }
    } catch (err) {
      setError('网络请求失败')
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  // 页面加载时获取数据
  useEffect(() => {
    const id = parseInt(Taro.getCurrentInstance().router?.params.questionnaireId || '1')
    fetchQuestionnaire(id)
  }, [])

  // 更新题目答案
  const updateAnswer = (questionId: number, value: string | string[]) => {
    setAnswers(prev => ({ ...prev, [questionId]: value }))
    
    // 立即判断是否正确
    const question = questionnaire?.questions.find(q => q.id === questionId)
    if (question) {
      const isCorrect = 
        JSON.stringify(value) === JSON.stringify(question.correctAnswer)
      setAnswerStatus(prev => ({
        ...prev,
        [questionId]: isCorrect ? 'correct' : 'incorrect'
      }))
      setShowAnalysis(true)
    }
  }

  // 更新当前题目索引
  const updateIndex = (newIndex: number) => {
    if (newIndex < 0 || newIndex >= (questionnaire?.questions.length || 0)) return
    setCurrentIndex(newIndex)
    setShowAnalysis(false) // 切换题目时隐藏解析
  }

  // 滑动事件处理
    const [touchStartX, setTouchStartX] = useState<number>(0)
    const handleTouchStart = (e: any) => {
      setTouchStartX(e.touches[0].clientX)
    }
    const handleTouchEnd = (e: any) => {
      const deltaX = e.changedTouches[0].clientX - touchStartX
      if (deltaX < -50 && currentIndex < (questionnaire?.questions.length || 1) - 1) {
        updateIndex(currentIndex + 1)
      }
      if (deltaX > 50 && currentIndex > 0) {
        updateIndex(currentIndex - 1)
      }
    }

  // 获取当前题目
  const currentQuestion = questionnaire?.questions[currentIndex]

  return (
    <View className='survey-container'>
      {/* 导航栏 */}
      <View className='header'>
        <View className='left'>
          <Button className='back-btn' onClick={() => Taro.navigateTo({ url: '/pages/home/index' })}>
            <Text>《</Text>
          </Button>
          
        </View>
        <View className='tabs'>
          <Text className='tab active'>答题</Text>
        </View>
        <View className='right'>
          
        </View>
      </View>

      {/* 题目内容 */}
      {!loading && !error && currentQuestion && (
        <View className='question-container'
          onTouchStart={handleTouchStart}
          onTouchEnd={handleTouchEnd}
        >
          {/* 题目类型标签 */}
          <View className='question-type-tag'>
           单选 
          {/* 题目标题 */}
          <View className='question-title'>{currentQuestion.id}. {currentQuestion.title}</View>
          </View>

          

          {/* 选项列表 */}
          <RadioGroup onChange={(e) => updateAnswer(currentQuestion.id, e.detail.value)}>
            {currentQuestion.options && currentQuestion.options.map((option) => (
              <View key={option.key} className='option-item'>
                <Radio value={option.value}>
                  <View className={`radio-indicator ${answerStatus[currentQuestion.id]?.includes(option) ? (answerStatus[currentQuestion.id] === 'correct' ? 'correct' : 'incorrect') : ''}`}>
                    {answerStatus[currentQuestion.id]?.includes(option) ? (answerStatus[currentQuestion.id] === 'correct' ? '✓' : '✗') : ''}
                  </View>
                  {option}
                </Radio>
              </View>
            ))}
          </RadioGroup>

          {/* 答案展示 */}
          {showAnalysis && (
            <View className='answer-box'>
              <Text>答案</Text>
              <Text className='answer-value'>{currentQuestion.correctAnswer}</Text>
            </View>
          )}

          {/* 解析区域 */}
          {showAnalysis && (
            <View className='analysis-section'>
              <View className='title-bar'>
                <Text>试题详解</Text>
                <Button className='report-btn'>试题纠错</Button>
              </View>
              <View className='analysis-tabs'>
                <Text className={`tab `}>AI解析</Text>

              </View>
              <View className='analysis-content'>
                <Text>{}</Text>
        
              </View>
              
            </View>
          )}
        </View>
      )}

      {/* 底部操作栏 */}
      <View className='footer'>
        <Button className='collect-btn'>
          <View className='star-icon'></View>
          <Text>收藏</Text>
        </Button>
        <View className='stats'>
          <View className='correct'>
            <View className='check-icon'></View>
            <Text>0</Text>
          </View>
          <View className='wrong'>
            <View className='cross-icon'></View>
            <Text>1</Text>
          </View>
        </View>
        <Button className='card-btn'>
          <View className='card-icon'></View>
          <Text>答题卡</Text>
        </Button>
      </View>
    </View>
  )
}
